package cn.wolfcode.controller;

import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/list")
    @RequiredPermission(name = "查询角色", expression = "role:list")
    public String list(Model model, QueryObject qo) {
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageResult", pageInfo);
        return "role/list";
    }

    /*@RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){
        try{roleService.delete(id);
            return new JsonResult();
        }catch(Exception e){
            e.printStackTrace();
            return new JsonResult(false,"删除失败");
        }
    }
*/
    @RequestMapping("/delete")
    @RequiredPermission(name = "角色删除", expression = "role:delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        try {
            roleService.delete(id);
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "删除失败");
        }
    }

    @RequestMapping("/input")
    @RequiredPermission(name = "角色编辑", expression = "role:input")
    public String input(Long id, Model model) {
        if (id != null) {
            model.addAttribute("role", roleService.selectOne(id));
        }
        model.addAttribute("pageResult", permissionService.selectAll());
        return "role/input";
    }

    @RequestMapping("/saveOrUpdate")
    @RequiredPermission(name = "角色保存或更新", expression = "role:saveOrUpdate")
    public String saveOrUpdate(Role role, Long[] ids) {
        if (role.getId() != null) {
            roleService.update(role, ids);
        } else {
            roleService.save(role, ids);
        }
        return "redirect:/role/list.do";
    }
}
